package com.tuyulong.mybatis.interceptor;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;

import com.tuyulong.mybatis.annotation.CryptField;
import com.tuyulong.mybatis.utils.RSAUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @describe: 查询拦截器
 * 查询条件加密使用方式：使用 @Param("decrypt")注解的自定义类型
 * 返回结果解密使用方式： （不支持lambdaQuery写法！！！）
 * ①在自定义的DO上加上注解 CryptEntity
 * ②在需要加解密的字段属性上加上 CryptField
 * @author: tuyulong
 * @create: 2022-12-05 16:14
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class})
})
public class QueryInterceptor implements Interceptor {
    /**
     * 查询参数名称，ParamMap的key值
     */
    private static final String DECRYPT = "decrypt";

    private final static Logger logger = LoggerFactory.getLogger(QueryInterceptor.class);


    @Value("${db.data.check_sign:false}")
    private boolean checkSign;


    @Autowired
    private UpdateInterceptor updateInterceptor;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        //获取查询参数，查询条件是否需要加密
        Object[] args = invocation.getArgs();
        Object parameter = args[1];
        Object result = null;
        //设置执行标识
        boolean flag = true;
        //判断参数是否带有加密注解
        if (parameter instanceof MapperMethod.ParamMap) {
            Map paramMap = (Map) parameter;
            if (paramMap.containsKey(DECRYPT)) {
                Object queryParameter = paramMap.get(DECRYPT);
                if (updateInterceptor.needToCrypt(queryParameter)) {
                    //执行sql，还原加密后的报文
                    MappedStatement mappedStatement = (MappedStatement) args[0];
                    result = updateInterceptor.proceed(invocation, mappedStatement, queryParameter);
                    flag = false;
                }
            }
        }
        //是否需要执行
        if (flag) {
            result = invocation.proceed();
        }
        if (Objects.isNull(result)) {
            return null;
        }
        // 返回列表数据，循环检查
        if (result instanceof ArrayList) {
            ArrayList resultList = (ArrayList) result;
            if (!CollectionUtils.isEmpty(resultList) && updateInterceptor.needToCrypt(resultList.get(0))) {
                for (Object o : resultList) {
                    decrypt(o);
                }
            }
        } else if (updateInterceptor.needToCrypt(result)) {
            decrypt(result);
        }
        //返回结果
        return result;
    }

    /**
     * @param resultObject 需要解密的对象
     * @return
     * @throws Exception
     */
    private Object decrypt(Object resultObject) throws Exception {
        // 取出resultType的类
        Class<?> resultCls = resultObject.getClass();
        Field[] fields = resultCls.getDeclaredFields();
        Map<String, String> map = new HashMap<>(16);
        for (Field field : fields) {
            // 获取所有被CryptField注解的字段
            if (field.isAnnotationPresent(CryptField.class)) {
                field.setAccessible(true);
                Object obj = field.get(resultObject);
                if (obj instanceof String) {
                    String val = obj.toString();
                    String decrypt = RSAUtils.decrypt(val);
                    map.put(field.getName(),decrypt);
                    field.set(resultObject,  decrypt);

                    //验签
                    String signFieldName = field.getAnnotation(CryptField.class).value();
                    if (StrUtil.isNotBlank(signFieldName)) {
                        Object signValue = ReflectUtil.getFieldValue(resultObject, signFieldName);
                        if (Objects.nonNull(signValue) && StrUtil.isNotBlank(signValue.toString())) {
                            if (!RSAUtils.verifySign(decrypt, signValue.toString()) && checkSign) {
                                throw new RuntimeException("验签失败，请检查数据!");
                            }
                        }
                    }
                }
            }
        }
        // 如果对象中有与加密字段相同的字段，则将加密字段赋值过去
        for (Field field : fields) {
            String value = map.get(field.getName() + "Encrypt");
            if (StrUtil.isNotBlank(value)) {
                field.setAccessible(true);
                field.set(resultObject,value );
            }
            /*if (field.getName().contains("Sign")
                    && StringUtils.isNotBlank(map.get(field.getName().replace("Sign", "")))) {
                field.setAccessible(true);
                if (Objects.nonNull(field.get(resultObject)) && StringUtils.isNotBlank(field.get(resultObject).toString())) {
                    String sign = (String) field.get(resultObject);
                    String data = map.get(field.getName().replace("Sign", ""));
                    if (!EncryptUtils.verifySign(data, sign)) {
                        logger.info("EncryptUtils verifySign data:{}, sign:{}", data, sign);
                        throw ApiException.businessError("验签失败，请检查数据!");
                    }
                }
            }*/
        }
        return resultObject;
    }
}